package com.nuanshui.heatedloan.extension.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.nuanshui.heatedloan.util.dwz.AjaxObject;

@Component
public class SysExceptionHandler implements HandlerExceptionResolver {
	Log logger = LogFactory.getLog(SysExceptionHandler.class);

	@Override
	public ModelAndView resolveException(final HttpServletRequest request,
			final HttpServletResponse response, final Object handler,
			final Exception ex) {
		AjaxObject ajaxObject = new AjaxObject("修改成功",false);
		ajaxObject.setErrorCode(AjaxObject.STATUS_CODE_FAILURE);
		PrintWriter out = null;
		ex.printStackTrace();
		if (ex instanceof CommonSysException) {// 如果是系统自定义异常
			ajaxObject.setMessage(ex.getMessage());

		} else if (ex instanceof ParamsErrorException) {// 必输的参数为空
			ajaxObject.setMessage(ex.getMessage());

		} else if (ex instanceof ResultCodeException) {// 自定义参数内容
			ajaxObject.setMessage(ex.getMessage());
		} else if (ex instanceof DataExistException) {// unqie数据库中已经存在数据
			ajaxObject.setMessage(ex.getMessage());
		} else if (ex instanceof RuntimeException) {// 运行时异常
			ajaxObject.setMessage(ex.getMessage());
		}
		try {
			
			response.setContentType("text/html;charset=UTF-8");
			response.setLocale(new java.util.Locale("zh", "CN"));
			out = response.getWriter();
			out.println(new Gson().toJson(ajaxObject));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
		return new ModelAndView();
	}

}
